package com.dymall.payment.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dymall.common.api.CheckoutClient;
import com.dymall.common.api.OrderClient;
import com.dymall.common.api.UserClient;
import com.dymall.common.domain.dto.CheckoutReqDTO;
import com.dymall.common.exception.BadRequestException;
import com.dymall.common.exception.BizIllegalException;
import com.dymall.common.exception.ForbiddenException;
import com.dymall.common.util.UserContext;
import com.dymall.payment.domain.dto.CreditCardInfo;
import com.dymall.payment.domain.pojo.CreditCard;
import com.dymall.payment.domain.pojo.Payment;
import com.dymall.payment.domain.dto.req.ChargeReq;
import com.dymall.payment.domain.dto.resp.ChargeResp;
import com.dymall.payment.enums.PayStatus;
import com.dymall.payment.enums.PayType;
import com.dymall.payment.mapper.CreditCardMapper;
import com.dymall.payment.mapper.PaymentMapper;
import com.dymall.payment.service.IPaymentService;
import com.dymall.payment.util.CreditUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.UUID;

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements IPaymentService {
    @Autowired
    private PaymentMapper paymentMapper;  // 用于操作支付记录表

    @Autowired
    private CreditCardMapper creditCardMapper;

    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private CreditUtil creditUtil;

    @Autowired
    private CheckoutClient checkoutClient;

    @Transactional
    @Override
    public ChargeResp charge(ChargeReq req) {
        Long userId = UserContext.getUser();
        Long orderId = req.getOrderId();
        Integer amount = req.getAmount();
        String password = req.getPassword();

        // 验证用户信息
        if (userId == null || orderId == null || amount == null || password == null) {
            throw new BadRequestException("支付请求参数无效");
        }

        // 查询当前用户绑定的信用卡信息
        CreditCard userCreditCard = creditCardMapper.getUserCreditCard(userId);
        System.out.println(userCreditCard);

        // 验证提供的信用卡是否与当前用户匹配
        if (userCreditCard == null) {
            throw new ForbiddenException("用户未绑定该信用卡");
        }

        // 转换实体
        CreditCardInfo userCreditCardInfo = new CreditCardInfo();
        userCreditCardInfo.setCardNum(userCreditCard.getCardNum());
        userCreditCardInfo.setCardCvv(userCreditCard.getCardCvv());
        userCreditCardInfo.setExpYear(userCreditCard.getExpYear());
        userCreditCardInfo.setExpMonth(userCreditCard.getExpMonth());

        if(!creditUtil.isCardMatched(userCreditCardInfo, req.getCreditCard())){
            throw new ForbiddenException("提供的信用卡信息与当前用户不匹配");
        }

        // 使用信用卡支付
        if (req.getCreditCard() != null) {
            CreditCardInfo creditCardInfo = req.getCreditCard();

            // 提取信用卡信息
            String cardNumber = creditCardInfo.getCardNum();
            int cvv = creditCardInfo.getCardCvv();
            int expirationYear = creditCardInfo.getExpYear();
            int expirationMonth = creditCardInfo.getExpMonth();

            // 信用卡支付验证
            boolean isCardValid = creditUtil.validateCreditCard(cardNumber, cvv, expirationYear, expirationMonth);

            if (isCardValid) {
                // 模拟支付成功
                // 扣减余额
                // 查询用户的余额
                Integer balance = userClient.getBalance(UserContext.getUser());

                // 验证余额是否足够
                if (balance < amount) {
                    throw new BizIllegalException("余额不足");
                }

                try {
                    // 扣减余额
                    userClient.deductMoney(password, amount);
                } catch (Exception e) {
                    throw new BizIllegalException("支付失败");
                }

                // 创建支付记录
                Payment payment = new Payment();
                payment.setUserId(userId);
                payment.setOrderId(orderId);
                payment.setAmount(amount);
                payment.setPayStatus(PayStatus.PAY_SUCCESS.getValue());    // 设置状态为支付成功
                payment.setPayAt(new Timestamp(System.currentTimeMillis()));  // 支付时间
                payment.setTransactionId(UUID.randomUUID().toString());  // 使用UUID生成交易ID
                paymentMapper.insert(payment);  // 插入支付记录

                // 标记订单已支付
                orderClient.markOrderPaySuccess(orderId);   // 状态设为2

                // 返回支付结果
                ChargeResp chargeResp = new ChargeResp();
                chargeResp.setTransactionId(payment.getTransactionId());
                return chargeResp;
            } else {
                throw new BadRequestException("信用卡信息无效");
            }
        } else {
            throw new BadRequestException("未提供信用卡信息");
        }
    }

}
